package com.erp.erp_servers.Email.Impl;

import com.erp.erp_dao.Email.EmailDao;
import com.erp.erp_entitys.Customer2Contact.Customer2ContactEntity;
import com.erp.erp_entitys.Customer2Contact.Customer2ContactExample;
import com.erp.erp_entitys.Dictionary.DictionaryEntity;
import com.erp.erp_entitys.Email.*;
import com.erp.erp_entitys.User.UserEntity;
import com.erp.erp_entitys.warehouse.entity.AnnexEntity;
import com.erp.erp_servers.Customer.ICustomerService;
import com.erp.erp_servers.Customer2Contact.ICustomer2ContactService;
import com.erp.erp_servers.CustomerContact.ICustomerContactService;
import com.erp.erp_servers.Dictionary.IDictionary2Service;
import com.erp.erp_servers.Email.EmailService;
import com.erp.erp_servers.Ftp.IFtpService;
import com.erp.erp_servers.User.IUserService;
import com.erp.utils.R;
import com.sun.mail.imap.IMAPFolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.mail.*;
import javax.mail.internet.MimeMessage;
import javax.mail.search.AndTerm;
import javax.mail.search.ComparisonTerm;
import javax.mail.search.SearchTerm;
import javax.mail.search.SentDateTerm;
import java.io.*;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


@Service
public class EmailServiceImpl implements EmailService {
    @Autowired
    EmailDao emailDao;
    @Autowired
    private  IUserService userService;
    @Autowired
    private IDictionary2Service dictionary2Service;
    @Autowired
    private  IFtpService iFtpService;
    @Autowired
    private  ICustomerService customerService;
    @Autowired
    ICustomerContactService customerContactService;
    @Autowired
    ICustomer2ContactService customer2ContactService;

    private static ServicerLink servicerLink=new ServicerLink();



    //将读取协议信息从数据库拉取出来
    @Override
    public List<email_Pop3> selectAllEmail_Pop3() {
        return emailDao.selectAllEmail_Pop3();
    }

    @Override
    public List<email_Pop3> selectAllEmail_Pop3byUserCode(String code) {
        return emailDao.selectAllEmail_Pop3byUserCode(code);
    }

    //根据pop3id获取全部邮件并根据时间排序
    @Override
    public List<email_email> selectAllEmailBypop3IDS(emailOrder order) {
        if(order.getSelect()!=null&&order.getSelect()!=""){
            order.setEmailClass(0);
        }
        return emailDao.selectAllEmailBypop3IDS(order);
    }

    @Override
    public void updateEmail_Pop3(int pop3_id, String uid) {
        emailDao.updateEmail_Pop3(pop3_id, uid);
    }

    @Override
    public int addEmail_email(email_email email) {
        return emailDao.addEmail_email(email);
    }

    @Override
    public void insertEmail_adjunct(email_adjunct email_adjunct) {
        emailDao.insertEmail_adjunct(email_adjunct);
    }

    @Override
    public List<email_adjunct> selectAdjunctForEmail_ID(int email_id) {
        return emailDao.selectAdjunctForEmail_ID(email_id);
    }

    @Override
    public email_adjunct selectAdjunctForAdjunct_ID(int adjunct_id) {
        return emailDao.selectAdjunctForAdjunct_ID(adjunct_id);
    }

    @Override
    public email_email selectEmailByEmail_id(int email_id) {
        return emailDao.selectEmailByEmail_id(email_id);
    }

    @Override
    public email_Pop3 selectPOP3Bypop3_id(int pop3_id) {
        return emailDao.selectPOP3Bypop3_id(pop3_id);
    }

    @Override
    public void updateEmail_emailReady1(int email_id) {
        emailDao.updateEmail_emailReady1(email_id);
    }
    @Override
    public void updateEmail_emailReady2(int email_id) {
        emailDao.updateEmail_emailReady2(email_id);
    }
    @Override
    public void updateUpAdjunct(email_adjunct adjunct) {
        emailDao.updateUpAdjunct(adjunct);
    }

    @Override
    public List<email_adjunct> selectAllAdjunct() {
        return emailDao.selectAllAdjunct();
    }

    @Override
    public List<email_email> selectAllEmailbyPOP3_id(int pop3_id) {
        return emailDao.selectAllEmailbyPOP3_id(pop3_id);
    }

    @Override
    public int insertBox(email_box box) {
        return emailDao.insertBox(box);
    }

    @Override
    public void insertBox_Email(email_box_emailid emailid) {
        emailDao.insertBox_Email(emailid);
    }

    @Override
    public List<email_email> selectEmailForBoxID(int boxID) {
        return emailDao.selectEmailForBoxID(boxID);
    }

    @Override
    public email_box selectSearchBox(String code) {
        return emailDao.selectSearchBox(code);
    }

    @Override
    public List<email_email> selectEmailForEmailID(List<Integer> emailIDs) {
        return emailDao.selectEmailForEmailID(emailIDs);
    }

    @Override
    public void deleteBox(int boxID) {
        emailDao.deleteBox(boxID);
    }

    @Override
    public void deleteBox_email(int boxID) {
        emailDao.deleteBox_email(boxID);
    }

    @Override
    public List<email_box> selectAllBox(String code) {
        return emailDao.selectAllBox(code);
    }

    @Override
    public int insertSearch(searchEmail searchEmail) {
        return emailDao.insertSearch(searchEmail);
    }

    @Override
    public void deleteSearch(int searchID) {
        emailDao.deleteSearch(searchID);
    }

    @Override
    public searchEmail selectSearch(int searchID) {
        return emailDao.selectSearch(searchID);
    }

    @Override
    public void insertPop3(email_Pop3 pop3) {
        emailDao.insertPop3(pop3);
    }

    @Override
    public void updatePop3(email_Pop3 pop3) {

        emailDao.updatePop3(pop3);
    }

    @Override
    public void deletePop3(int pop3id) {
        emailDao.deletePop3(pop3id);
    }

    @Override
    public void insetStmp(email_smtp smtp) {
        emailDao.insetStmp(smtp);
    }

    @Override
    public void updateStmp(email_smtp smtp) {
        emailDao.updateStmp(smtp);
    }

    @Override
    public void deleteStmp(int smtoID) {
        emailDao.deleteStmp(smtoID);
    }

    @Override
    public List<email_smtp> selectStmp(String code) {
        return emailDao.selectStmp(code);
    }

    @Override
    public email_smtp selectStmpById(int stmpid) {
        return emailDao.selectStmpById(stmpid);
    }

    @Override
    public void insertEmail_mass(email_mass mass) {
        emailDao.insertEmail_mass(mass);
    }

    @Override
    public void insertTag(int emailID, String tag) {
        emailDao.insertTag(emailID, tag);
    }

    @Override
    public void deleteTag(int emailID) {
        emailDao.deleteTag(emailID);
    }

    @Override
    public void insertStar(int emailID) {
        emailDao.insertStar(emailID);
    }

    @Override
    public void deleteStar(int emailID) {
        emailDao.deleteStar(emailID);
    }

    @Override
    public List<email_email> selectAllEmailbyPOP3_idNoReady(int pop3_id) {
        return emailDao.selectAllEmailbyPOP3_idNoReady(pop3_id);
    }

    @Override
    public List<email_email> selectAllEmailNoReady() {
        return emailDao.selectAllEmailNoReady();
    }

    @Override
    public List<email_email> searchEmail(searchEmail searchEmail) {
        return emailDao.searchEmail(searchEmail);
    }

    @Override
    public void changeXinbiao0(Integer emailID) {
        emailDao.changeXinbiao0(emailID);
    }

    @Override
    public void changeXinbiao1(Integer emailID) {
        emailDao.changeXinbiao1(emailID);
    }

    @Override
    public void changeTag(Tag tt) {
        emailDao.changeTag(tt);
    }

    @Override
    public List<email_email> selectApproveEmailByCode(String code) {
        return emailDao.selectApproveEmailByCode(code);
    }

    @Override
    public List<email_email> selectEmailByGaoji(searchEmail search) {
        return emailDao.selectEmailByGaoji(search);
    }

    @Override
    public email_box selectBoxById(Integer box_id) {
        return emailDao.selectBoxById(box_id);
    }

    @Override
    public void updateSearch(searchEmail search) {
        emailDao.updateSearch(search);
    }

    @Override
    public void updateBox(email_box box) {
        emailDao.updateBox(box);
    }

    @Override
    public void updateEmailClass(changeEmailClass chage) {
        emailDao.updateEmailClass(chage);
    }

    @Override
    public void changeEmailReady(changeEmailReady chage) {
        emailDao.changeEmailReady(chage);
    }

    @Override
    public void changeAllEmailReady(List<email_Pop3> pop3s) {
        emailDao.changeAllEmailReady(pop3s);
    }

    @Override
    public List<email_email> selectEmailByAnswer(List<email_Pop3> pop3s) {
        return emailDao.selectEmailByAnswer(pop3s);
    }

    @Override
    public List<email_email> selectEmailByready(List<email_Pop3> pop3s) {
        return emailDao.selectEmailByready(pop3s);
    }

    @Override
    public void updateReadStatue(Integer emailID) {
        emailDao.updateReadStatue(emailID);
    }

    @Override
    public int insertEmail_account(email_account account) {
        return emailDao.insertEmail_account(account);
    }

    @Override
    public void deleteEmail_account(email_account account) {
        emailDao.deleteEmail_account(account);
    }

    @Override
    public List<email_account> selectEmail_accountBycode(String code) {
        return emailDao.selectEmail_accountBycode(code);
    }

    @Override
    public void updateEmail_account(email_account account) {
        emailDao.updateEmail_account(account);
    }

    @Override
    public email_account selectEmail_accountById(Integer ccid) {
        return emailDao.selectEmail_accountById(ccid);
    }

    @Override
    public void updateEmail_accountStatues() {//acc表，pop表，smtp表修改
        emailDao.updateEmail_accountStatues();
        emailDao.updateEmail_Pop3Statues();
        emailDao.updateEmail_SmtpStatues();
    }

    @Override
    public void insertTemplate(email_template template) {
        emailDao.insertTemplate(template);
    }

    @Override
    public void deleteTemplate(email_template template) {
        emailDao.deleteTemplate(template);
    }

    @Override
    public void updateTemplate(email_template template) {
        emailDao.updateTemplate(template);
    }

    @Override
    public List<email_template> selectTemplates(String code) {
        return emailDao.selectTemplates(code);
    }

    @Override
    public void updateTemplateNodefault(String code) {
        emailDao.updateTemplateNodefault(code);
    }

    @Override
    public email_template selectTemplateByid(Integer template_id) {
        return emailDao.selectTemplateByid(template_id);
    }

    @Override
    public void inserteDeploy(email_deploy deploy) {
        emailDao.inserteDeploy(deploy);
    }

    @Override
    public email_deploy selectDeploy(String Code) {
        return emailDao.selectDeploy(Code);
    }

    @Override
    public void updateDeploy(email_deploy deploy) {
        emailDao.updateDeploy(deploy);
    }

    @Override
    public List<email_email> selectdraft(String code) {
        return emailDao.selectdraft(code);
    }

    @Override
    public List<email_box_emailid> selectEmailForBoxIsExist(Integer boxid, Integer emailid) {
        return emailDao.selectEmailForBoxIsExist(boxid, emailid);
    }
    @Override
    public List<email_box_emailid> selectAllEmailForBoxIsExist(Integer emailid) {
        return emailDao.selectAllEmailForBoxIsExist(emailid);
    }
    @Override
    public void insertEmailRules(EmailRules rule) {
        emailDao.insertEmailRules(rule);
    }

    @Override
    public List<EmailRules> selectEmailRulesBycode(String code) {
        return emailDao.selectEmailRulesBycode(code);
    }

    @Override
    public EmailRules selectEmailRulesByID(Integer id) {
        return emailDao.selectEmailRulesByID(id);
    }

    @Override
    public void updateEmailRules(EmailRules rule) {
        emailDao.updateEmailRules(rule);
    }

    @Override
    public void deleteEmailRules(Integer id) {
        emailDao.deleteEmailRules(id);
    }

    @Override
    public Integer selectNowEmail(email_nowEmail ne) {
        return emailDao.selectNowEmail(ne);
    }

    @Override
    public email_email selectnotFind(String address) {
        return emailDao.selectnotFind(address);
    }

    @Override
    public Map<String, Integer> notFind(List<String> address) {
        Map<String, Integer> notfind = new HashMap<>();
        //根据用户code获取到ids
        for (String add : address) {
            email_email e = emailDao.selectnotFind(add);
            String Rectime = e.getRecDate();//收件时间   外部给内部发送的邮件发送时间
            String sendtime = e.getSendDate();//发件时间   内部给外部发送邮件的发送时间
            String senderAddresser = e.getSenderAddresser();
            String address1 = e.getRecipientAddress();//带  ";"
            if(senderAddresser==add){
                notfind.put(add,getDay(Rectime));
            }else {
                notfind.put(add,getDay(sendtime));
            }

        }
        return notfind;
    }


    public static int getDay(String date) {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Long days = null;
        try {
            Date currentTime = dateFormat.parse(dateFormat.format(new Date()));//现在系统当前时间
            Date pastTime = dateFormat.parse(date);//过去时间
            long diff = currentTime.getTime() - pastTime.getTime();
            days = diff / (1000 * 60 * 60 * 24);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return days.intValue();
    }

    //下载所有邮件元数据
    @Override
    public int upDateEmail() {
        List<email_Pop3> pop3s = this.selectAllEmail_Pop3();
        if(pop3s.size()>0){
            for (email_Pop3 pop : pop3s) {
                try {
                    //返回true，代表可以继续执行，否则结束
                    boolean contin=ServerciEmailUnit.contin(pop,emailDao);
                    if(contin==true){
                        getAllemailAuto(pop);
                    }else{
                        continue;
                    }
                }catch (Exception e){
                    boolean contin=ServerciEmailUnit.contin(pop,emailDao);
                    if(contin==false){
                        emailDao.deleteAuto(new emailAuto(pop.getPop3_id()));
                    }
                    System.out.println("pop3id="+pop.getPop3_id()+":updateEmail  errer="+e);
                }
            }
        }
        return 1;
    }
    //定时器下载所有邮件元数据
    @Override
    public void getAllemailAuto(email_Pop3 pop){
        emailDao.addAuto(new emailAuto(pop.getPop3_id(),1,ServerciEmailUnit.getNowSqlDate()));
        System.out.println("编号:"+pop.getPop3_id()+"启动下载邮件元数据");
        try {
            String READ="INBOX";
            for(int x=0;x<2;x++){
                Folder folder = servicerLink.getFolder(pop,READ);
                IMAPFolder inbox = (IMAPFolder) folder;
                if(inbox!=null){
                    //提取最后三位uuid进行比对，获取最新的邮件
                    Integer uuid =Math.abs(Integer.parseInt(ServerciEmailUnit.getTreeUUid(pop,READ)));
                    int count=inbox.getMessageCount();//邮箱总数
                    int i=1;
                    int j=1;//控制客户邮箱是否已经全部提取，全部提取为2；
                    boolean wrong=false;//查看邮箱在获取message时是否出现问题，可能会无法获取message，此时应当跳过
                    List<Integer> firstEmail=new ArrayList<>();
                    while(true){//每次取10条数据，如果达到条件，返回false停止，否则返回true继续
                        Message[] messages=null;
                        if(i==1){
                            if(count<=11){
                                messages = inbox.getMessages(1,count);
                                j=2;
                            }else{
                                messages = inbox.getMessages(count-(10*i),count);}
                        }else{
                            if((count-(10*i))<=1){
                                messages = inbox.getMessages(1,count-(10*(i-1)+1));
                                j=2;
                            }else {
                                messages = inbox.getMessages(count - (10 * i), count - (10 * (i - 1) + 1));
                            }
                        }
                        boolean b = downMessages(messages, pop, inbox, uuid,firstEmail,READ,wrong);
                        if(b==false){
                            break;
                        }
                        if(j==2){
                            break;
                        }
                        i++;
                        System.out.println("编号pop3_id:"+pop.getPop3_id()+"正在第"+i+"次收件");
                    }
                    if(wrong==false){
                        if(READ.equals("INBOX")){
                            //获取最新的uuid作为pop_email_num，用作新邮件判断
                            List<email_email> email_emails = emailDao.selectLastMessage(pop.getPop3_id());
                            String last1=email_emails.get(0).getMessage_id()+"";
                            updateEmail_Pop3(pop.getPop3_id(), last1);
                        }else{
                            //获取最新的uuid作为pop_email_num，用作新邮件判断
                            List<email_email> email_emails = emailDao.selectLastSendMessage(pop.getPop3_id());
                            if(email_emails.get(0).getMessage_id()<-1){
                                String last1=email_emails.get(0).getMessage_id()+"";
                                emailDao.updateSendEmail_Pop3(pop.getPop3_id(), last1);
                            }
                        }
                    }

                }else{
                    System.out.println(pop.getPop3_id()+"在接收邮件时发现账号失效");
                    ServerciEmailUnit.stopPop(pop,this);
                }
                READ="已发送";
            }

        }catch (Exception e){
            System.out.println("getAllemailAuto出错:"+e);
            emailDao.deleteAuto(new emailAuto(pop.getPop3_id()));
        }
        System.out.println("编号:"+pop.getPop3_id()+"结束下载邮件元数据");
        emailDao.deleteAuto(new emailAuto(pop.getPop3_id()));
    }

    public boolean downMessages(Message[] messages,email_Pop3 pop,IMAPFolder inbox,Integer uuid,List<Integer> firstEmail,String READ,boolean wrong){
        int wrongNum=0;
        try{
            if(inbox.exists()==false){
                inbox= (IMAPFolder) servicerLink.openFolder(pop,READ);
            }
        }catch (Exception e){
            System.out.println("downMessages方法中inbox获取出错"+e);
            return false;
        }
        for (int i = 0; i < messages.length; i++) {
            try {
                MimeMessage message = (MimeMessage) messages[messages.length - 1 - i];//从最新到最旧获取邮件
                String uid = inbox.getUID(message) + "";//获取当前邮件的uuid
                if(firstEmail.size()==0){
                    firstEmail.add(Integer.parseInt(uid));
                    pop.setPop_email_num(uid);
                }
                if (message != null) {//可能报错： Failed to load IMAP envelope，smtp发送（程序）的邮件不能用imap接收
                    //获取到发件时间
                    String sqlDate = null;
                    if (message.getSentDate() != null) {
                        sqlDate = ServerciEmailUnit.getSqlDate(message.getSentDate());
                    }
                    //第二重判断，判断是否新邮件，如果最新的三位都符合已存储的邮件，既新邮件到此结束
                    Integer ud=Integer.parseInt(uid);
                    if (ud<=uuid) {
                        return false;
                    }
                    //第三重判断，时间判断   根据设置收取的时间条件  0：默认三个月；1:6个月；2:9个月；3：全部
                    if (pop.getPop_getTime() != 3) {
                        Date saveDate = ServerciEmailUnit.saveDate(pop.getPop_getTime());
                        long time = saveDate.getTime();//2020.8.20
                        Date emailDate = message.getSentDate();
                        if(emailDate!=null){
                            long time1 = emailDate.getTime();//2020.8.19
                            if ((time - time1) > 0) {
                                return false;
                            }
                        }
                    }
                    //将邮件元数据进行保存入口
                    UserEntity user = userService.selectUserByCode(pop.getPop3_user_id());
                    if(READ.equals("已发送")){
                        uid="-"+uid;
                    }
                    email_email email = ServerciEmailUnit.saveEmail(message, uid, pop.getPop3_server(), sqlDate, pop, this, pop.getEmail_adress(), user,customerContactService,customerService,READ);
//                    servicerLink.addEmail(email);
                }
            } catch (Exception e) {
                //因为该处极个别邮件可能会因为 pop3收取邮件导致报错
                System.out.println("编号:"+pop.getPop3_id()+"执行具体收件任务出错downMessages"+e);
                System.out.println("wrongNum="+wrongNum);
                wrongNum++;
                continue;
            }
        }
        if(wrongNum>5){
            return false;
        }else{
            return true;
        }
    }

    //手动下载所有邮件元数据，进行去重复
    @Override
    public void getAllemail(email_Pop3 pop) throws MessagingException {
        //返回true，代表可以继续执行，否则结束
        try {
            boolean contin=ServerciEmailUnit.contin(pop,emailDao);
            if(contin==true) {
                //操作唯一
                String READ = "INBOX";
                for (int x = 0; x < 2; x++) {
                    emailDao.addAuto(new emailAuto(pop.getPop3_id(), 0, ServerciEmailUnit.getNowSqlDate()));
                    IMAPFolder inbox = (IMAPFolder) servicerLink.getFolder(pop, READ);
                    //提取最后三位uuid进行比对，获取最新的邮件
                    Integer uuid =Math.abs(Integer.parseInt(ServerciEmailUnit.getTreeUUid(pop,READ)));
                    int count = inbox.getMessageCount();//邮箱总数
                    int i = 1;
                    int j = 1;
                    boolean wrong=false;
                    List<Integer> firstEmail = new ArrayList<>();
                    while (true) {//每次取10条数据，如果达到条件，返回false停止，否则返回true继续
                        Message[] messages = null;
                        if (i == 1) {
                            if (count <= 11) {
                                messages = inbox.getMessages(1, count);
                                j = 2;
                            } else {
                                messages = inbox.getMessages(count - (10 * i), count);
                            }
                        } else {
                            if ((count - (10 * i)) <= 1) {
                                messages = inbox.getMessages(1, count - (10 * (i - 1) + 1));
                                j = 2;
                            } else {
                                messages = inbox.getMessages(count - (10 * i), count - (10 * (i - 1) + 1));
                            }
                        }
                        boolean b = downMessages(messages, pop, inbox, uuid, firstEmail, READ, wrong);
                        if (b == false) {
                            break;
                        }
                        if (j == 2) {
                            break;
                        }
                        i++;

                    }
                    if(wrong==false){
                        if (READ.equals("INBOX")) {
                            //获取最新的uuid作为pop_email_num，用作新邮件判断
                            List<email_email> email_emails = emailDao.selectLastMessage(pop.getPop3_id());
                            String last1 = email_emails.get(0).getMessage_id() + "";
                            updateEmail_Pop3(pop.getPop3_id(), last1);
                        } else {
                            //获取最新的uuid作为pop_email_num，用作新邮件判断
                            List<email_email> email_emails = emailDao.selectLastSendMessage(pop.getPop3_id());
                            if (email_emails.get(0).getMessage_id() < -1) {
                                String last1 = email_emails.get(0).getMessage_id() + "";
                                emailDao.updateSendEmail_Pop3(pop.getPop3_id(), last1);
                            }
                        }
                    }
                    READ = "已发送";
                }
            }
        }catch (Exception e){
            emailDao.deleteAuto(new emailAuto(pop.getPop3_id()));
        }
        emailDao.deleteAuto(new emailAuto(pop.getPop3_id()));
    }

    @Override
    public email_email selectReuse(email_email email) {
        return emailDao.selectReuse(email);
    }

    //下载邮件附件及正文等
    //获取系统变量进行处置
    public static int getValue(List<DictionaryEntity> list){
        int x=0;
        for (DictionaryEntity d:list){
            if(d.getCode()!=null){
                x=Integer.parseInt(d.getName());
            }
        }
        return x;
    }
    //判断是否符合下载条件
    public boolean isTrue(IDictionary2Service dictionary2Service){
        //当前系统使用情况
        int diskLoad =new Double(ServerciEmailUnit.diskLoad()).intValue();
        int cpuLoad = ServerciEmailUnit.cpuLoad();
        int memoryLoad = ServerciEmailUnit.memoryLoad();
        //准许下载使用情况
        int disk= getValue(dictionary2Service.getValue(6, 52));
        int cpu= getValue(dictionary2Service.getValue(6, 51));
        int memory= getValue(dictionary2Service.getValue(6, 50));
        if(diskLoad<disk&&cpuLoad<cpu&&memoryLoad<memory){
            return true;
        }else{
            return false;
        }
    }
    //下载单个邮件
    @Override
    public R<String> upLoadAdjunctOne(Integer emailID) throws Exception {
        email_email email = this.selectEmailByEmail_id(emailID);
        String READ="INBOX";
        if (email.getMessage_id()<0&&email.getMessage_id()!=-1){
            READ="已发送";
        }
        //如果ready==1，则已经下载完毕，==0，未下载，将附件信息提取出来
        try {
            if (email.getReadyStatue() == 0 ||email.getReadyStatue() == 2) {
                email_Pop3 pop3 = this.selectPOP3Bypop3_id(email.getPop3_id());
                IMAPFolder folder =(IMAPFolder)  servicerLink.getFolder(pop3,READ);
                ServerciEmailUnit.upAdjunct(email, folder, pop3, this, iFtpService);
            }
        }catch (Exception e){
            System.out.println(e);
            servicerLink.deleteEmail(email);
        }
        return R.build("true");
    }

    //下载全部邮件的附件
    @Override
    public  void upLoadAdjunctMore(IDictionary2Service dictionary2Service, IFtpService iFtpService) {
        List<email_Pop3> pop3s = this.selectAllEmail_Pop3();
        for (email_Pop3 pop : pop3s) {
            servicerLink.addLink(pop,this);
        }
        List<email_email> emails = this.selectAllEmailNoReady();
        servicerLink.addEmail(emails);
        email_email ramEmail=null;
        while (true) {
            try {
                if (servicerLink.getRamEmail() != null) {
                    if(isTrue(dictionary2Service)==false){
                        break;
                    }
                    ramEmail = servicerLink.getRamEmail();
                    String READ="INBOX";
                    if (ramEmail.getMessage_id()<0&&ramEmail.getMessage_id()!=-1){
                        READ="已发送";
                    }
                    email_Pop3 pp = this.selectPOP3Bypop3_id(ramEmail.getPop3_id());
                    Folder folder = servicerLink.getFolder(pp,READ);
                    if(folder==null){
                        System.out.println(pp.getPop3_id()+"在附件下载中发现账号失效");
                        ramEmail.setCreateDate(ServerciEmailUnit.getNowSqlDate());
                        emailDao.updateEmailByCreateDate(ramEmail);
                        servicerLink.deleteAlLEmail();
                        break;
                    }
                    ServerciEmailUnit.upAdjunct(ramEmail, (IMAPFolder) folder, pp, this, iFtpService);
                    servicerLink.deleteEmail(ramEmail);
                    //停止条件设置
                    if (servicerLink.getEmailSize() == 0) {
                        break;
                    }
                }else{
                    break;
                }
            }catch (Exception e){
                System.out.println("uuid为："+ramEmail.getMessage_id()+"邮件下载出错");
                servicerLink.deleteEmail(ramEmail);
                this.updateEmail_emailReady2(ramEmail.getEmail_id());
                System.out.println(e);
            }
        }

    }

    //发送邮件（单次操作）
    @Override
    public R<String> sendEmailNow(email_message message){
        //直接发送
        //权限设置  差审批
        email_smtp smtp = this.selectStmpById(message.getStmpId());//message.getStmpId()
        UserEntity user = userService.selectUserByCode(smtp.getSmtp_user_id());
        email_deploy deploy = this.selectDeploy(user.getCode());
        String contenct = message.getContenct();//正文，需要提取正文图片
        List<String> matchString = ServerciEmailUnit.getMatchString(contenct);
        HashMap<String, String> pictures = new HashMap<>();//正文附图  map中，前为图片名,在正文中写法应为src=”cid:“，后为图片地址
        String fen = System.getProperty("file.separator");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String format = sdf.format(new Date());
        HashMap<String, String> basePices=new HashMap<>();////正文附图，用于存数据库  map中，前为图片名,在正文中写法应为src=”cid:“，后为图片地址
        String baseContext=message.getContenct();
        String tem = ServerciEmailUnit.getTem(dictionary2Service.getValue(6, 57));
        if(System.getProperty("os.name").toLowerCase().contains("win")){//测试使用，如果是windows系统
            tem="C:\\Users\\ceil\\Desktop\\tem\\";
        }
        for (String ur : matchString) {//出现图片变附件的原因，简单原因，相同图片相同名字，根本原因，cid一致
            String pathname = ur.split("pathname=")[1].split("&")[0];//获取到pathname值。该值为路径
            String filename = ur.split("filename=")[1];//文件名
            String cid1 = ServerciEmailUnit.getCid();
            String cid = "cid:" + cid1;
            pictures.put(cid, pathname + filename);
            String baseUrl="ftp"+ur.split("ftp")[1];
            basePices.put(cid,baseUrl);
            contenct = ServerciEmailUnit.getContext(contenct,ur,cid);//替换正文中的图片url
            baseContext=baseContext.replaceFirst(ur,baseUrl);
        }
        message.setContenct(contenct);
        message.setPictures(pictures);
        message.setStmpId(smtp.getSmtp_id());
        String sendSta = "发送成功";
        try {
            ServiceSendEmail.sendEmail(smtp, message, this, deploy,basePices,iFtpService,baseContext,customerContactService);
            //存入系统已发箱 ,只有元数据
            message.setSubject("(系统正在同步已发箱，请稍后)"+message.getSubject());
            this.saveEmail(message,user,10);
            emailDao.deleteCaoEmail(message.getEmail_id());
        } catch (Exception e) {
            sendSta = "发送失败，请检查账号设置";
        }
        //执行删除操作 删除文件夹 ftp服务器删除
        String deletePath =tem+fen+format;
        //ftp服务器删除暂无
        return R.build(sendSta);
        //清理空文件夹
    }


    @Override
    public void insetSendMessage(send_message send_message) {
        emailDao.insetSendMessage(send_message);
    }

    @Override
    public List<send_message> selectSendMessage() {
        return emailDao.selectSendMessage();
    }

    @Override
    public void deleteSend_message(int id) {
        emailDao.deleteSend_message( id);
    }

    //定时发送、延时发送邮件定时器任务
    @Override
    public  void sendEmailTiming(){
        try {
            List<send_message> send_messages = this.selectSendMessage();
            if(send_messages.size()>0){
                for(send_message s:send_messages){
                    Date sendDate = s.getDate();
                    email_message message = (email_message)ServerciEmailUnit.byte2obj(s.getMessage());
                    if(sendDate.before(new Date())){
                        this.sendEmailNow(message);
                        this.deleteSend_message(s.getId());
                    }
                }
            }
        }catch (Exception e){
            System.out.println("定时发送 errer");
        }

    }

    @Override
    public void ReturnEmailByBoxId(List<email_email> emails) {
        emailDao.ReturnEmailByBoxId(emails);
    }
    @Override
    public void ReturnEmailByBoxId1(List<email_email> emails) {
        emailDao.ReturnEmailByBoxId1( emails);
    }

    @Override
    public void deleteMuchEmail() {
        emailDao.deleteMuchEmail();
    }

    @Override
    public void deleteEmailInBox(int email_id) {
        emailDao.deleteEmailInBox(email_id);
    }

    @Override
    public void deleteUserBox(String address) {
        //当用户的邮箱进行维护后，需要先删除所有原有的内部联系人箱
        List<searchEmail> searchEmails = emailDao.selectSearchTmp(address);
        List<searchEmail> deletesearch=new ArrayList<>();
        List<email_box> deleteBox=new ArrayList<>();
        for(searchEmail s:searchEmails){
            //如果内部联系人箱子有这一条规则，那么留下来准备删除
            email_box email_box = emailDao.selectBoxBySearch(s.getSearch_id());
            if(email_box!=null){
                deleteBox.add(email_box);
                deletesearch.add(s);
            }
        }
        //删除箱子及规则，回退所有的邮件
        for(email_box email_box:deleteBox){
            try {
                //还原邮件
                List<email_email> email_emails = this.selectEmailForBoxID(email_box.getBox_id());
                List<email_email> e1=new ArrayList<>();//收件
                List<email_email> e2=new ArrayList<>();//发件
                for(email_email e:email_emails){
                    if(e.getMessage_id()==-1){
                        e2.add(e);
                    }else{
                        e1.add(e);
                    }
                }
                if(e1.size()>0){
                    this.ReturnEmailByBoxId(e1);//收件
                }
                if(e2.size()>0){
                    this.ReturnEmailByBoxId1(e2);//发件
                }
                //删除箱子
                this.deleteBox_email(email_box.getBox_id());
                this.deleteSearch(email_box.getSelect_rule());
                this.deleteBox(email_box.getBox_id());
            }catch (Exception e){
                System.out.println("出错："+e);
            }
        }
    }

    @Override
    public List<emailReadNum> selectEmailReadNum(List<Integer> pop3s) {
        return emailDao.selectEmailReadNum(pop3s);
    }

    @Override
    public email_box selectUserBoxByTwoCode(String code, String code1) {
        return emailDao.selectUserBoxByTwoCode(code, code1);
    }
    @Override
    public email_box selectUserBoxByTwoCode(String code) {
        List<searchEmail> searchEmails = emailDao.selectSearchBySendAddress(code);
        email_box email_box=null;
        for(searchEmail searchEmail:searchEmails){
            email_box box = emailDao.selectCustorBoxBySearch(searchEmail.getSearch_id());
            if(box!=null){
                email_box=box;
            }
        }
        return email_box;

    }
    //针对客户箱进行查询(修改批量)
    @Override
    public List<email_box> selectUserBoxByTwoCode1(String code) {
        List<searchEmail> searchEmails = emailDao.selectSearchBySendAddress(code);
        List<email_box> email_box=new ArrayList<>();
        for(searchEmail searchEmail:searchEmails){
            email_box box = emailDao.selectCustorBoxBySearch(searchEmail.getSearch_id());
            if(box!=null){
                email_box.add(box);
            }
        }
        return email_box;

    }
    /*检查所有的联系人对应到的联系人箱，更换规则
     * userClass  用户的类型  0 是用户 1是客户
     * type       操作类型（0新增，1修改，2删除）
     * oldemail   邮箱地址旧值
     * newEmail   邮箱地址新值
     * code       用户或客户编码
     * */
    @Override
    public boolean checkUserBox(List<email_custor> email_custors) {
        boolean re=true;
        try {
            for(email_custor email_custor:email_custors){
                emailDao.insertEmailCustor(email_custor);
            }
        }catch (Exception e){
            re=false;
        }
        checkCustor();
        return true;
    }

    @Override
    public void custorsIV() {
        //初始化客户箱
        /*CustomerContactExample example=new CustomerContactExample();
        CustomerContactExample.Criteria criteria = example.createCriteria();
        List<CustomerContactEntity> entities = customerContactService.selectByExample(example);
        for(CustomerContactEntity cust:entities){
            searchEmail searchEmail=new searchEmail();
            searchEmail.setSenderAddresser(cust.getEmail());
            searchEmail.setIsAdjunct(-1);
            searchEmail.setEmail_class(0);
            emailDao.insertSearch(searchEmail);
            email_box box=new email_box(cust.getName(),cust.getId()+"",ServerciEmailUnit.getNowSqlDate(),searchEmail.getSearch_id(),"-1",3);
            emailDao.insertBox(box);
        }*/
        Customer2ContactExample example=new Customer2ContactExample();
        Customer2ContactExample.Criteria criteria = example.createCriteria();
        List<Customer2ContactEntity> entities = customer2ContactService.selectByExample(example);
        for(Customer2ContactEntity cust:entities){
            searchEmail searchEmail=new searchEmail();
            searchEmail.setSenderAddresser(cust.getEmail());
            searchEmail.setIsAdjunct(-1);
            searchEmail.setEmail_class(0);
            emailDao.insertSearch(searchEmail);
            email_box box=new email_box(cust.getName(),cust.getId()+"",ServerciEmailUnit.getNowSqlDate(),searchEmail.getSearch_id(),"-1",3);
            emailDao.insertBox(box);
        }
    }

    @Override
    public void checkCustor() {
        try {
            List<email_custor> custors = emailDao.selectEmailCustor();
            for(email_custor custor:custors){
                try {
                    if(custor.getStatue()==0&&custor.getHandle()==1){//可用且是修改
                        if(custor.getCodeClass()==0){//可用且是修改内部联系人箱
                            List<email_box> boxes = emailDao.selectChangeBox(custor.getCode());
                            for(email_box box:boxes){
                                searchEmail searchEmail = emailDao.selectSearch(box.getSelect_rule());
                                searchEmail.setSenderAddresser(custor.getNewEmail());
                                emailDao.updateSearch(searchEmail);
                            }
                            emailDao.deleteEmailCustor(custor);
                        }else if(custor.getCodeClass()==1){//可用且是修改客户箱
                            List<email_box> boxes = emailDao.selectCustorBox(custor.getCode());
                            for(email_box box:boxes){
                                searchEmail searchEmail = emailDao.selectSearch(box.getSelect_rule());
                                searchEmail.setSenderAddresser(custor.getNewEmail());
                                emailDao.updateSearch(searchEmail);
                            }
                            emailDao.deleteEmailCustor(custor);
                        }
                    } else if(custor.getStatue()==0&&custor.getHandle()==0){//可用且是新增
                        if(custor.getCodeClass()==0){//可用且是新增内部联系人箱
                            emailDao.deleteEmailCustor(custor);
                        }else if(custor.getCodeClass()==1){//可用且是新增客户箱
                            searchEmail searchEmail=new searchEmail();
                            searchEmail.setSenderAddresser(custor.getNewEmail());
                            searchEmail.setIsAdjunct(-1);
                            searchEmail.setEmail_class(0);
                            emailDao.insertSearch(searchEmail);
                            email_box box=new email_box(custor.getName(),custor.getCode(),ServerciEmailUnit.getNowSqlDate(),searchEmail.getSearch_id(),"-1",3);
                            emailDao.insertBox(box);
                            emailDao.deleteEmailCustor(custor);
                        }
                    }else if(custor.getStatue()==0&&custor.getHandle()==2){//可用且是删除
                        List<email_box> boxes=new ArrayList<>();
                        if(custor.getCodeClass()==0){//可用且是删除内部联系人箱
                            boxes = emailDao.selectChangeBox(custor.getCode());
                        }else if(custor.getCodeClass()==1){//可用且是删除客户箱
                            boxes = emailDao.selectCustorBox(custor.getCode());
                        }
                        for(email_box box:boxes){
                            //还原邮件
                            List<email_email> email_emails = selectEmailForBoxID(box.getBox_id());
                            List<email_email> e1=new ArrayList<>();//收件
                            List<email_email> e2=new ArrayList<>();//发件
                            for(email_email e:email_emails){
                                if(e.getMessage_id()==-1){
                                    e2.add(e);
                                }else{
                                    e1.add(e);
                                }
                            }
                            if(e1.size()>0){
                                ReturnEmailByBoxId(e1);//收件
                            }
                            if(e2.size()>0){
                                ReturnEmailByBoxId1(e2);//发件
                            }
                            //删除箱子
                            deleteBox_email(box.getBox_id());
                            deleteSearch(box.getSelect_rule());
                            deleteBox(box.getBox_id());
                        }
                        emailDao.deleteEmailCustor(custor);
                    }else{//不可用

                    }
                }catch (Exception e){
                    custor.setStatue(1);
                    emailDao.updateEmailCustor(custor);
                }

            }
        }catch (Exception e){

        }
    }

    @Override
    public email_box selectSearchBySendAddress(String senderAddresser) {
        List<searchEmail> searchEmails = emailDao.selectSearchBySendAddress(senderAddresser);
        email_box box=null;
        for(searchEmail s:searchEmails){
            email_box email_box = emailDao.selectBoxBySearch(s.getSearch_id());
            if(email_box.getBox_grade()==3){//限定客户箱
                box=email_box;
            }
        }
        return box;
    }

    @Override
    public void setEmailSize(int id, int size) {
        emailDao.setEmailSize(id,size);
    }

    @Override
    public void deleteAuto(emailAuto emailAuto) {
        emailDao.deleteAuto(emailAuto);
    }

    @Override
    public List<email_email> selectEmeilBySuject() {
        return emailDao.selectEmeilBySuject();
    }

    @Override
    public void updateSubject(int email_id, String strr) {
        emailDao.updateSubject( email_id,  strr);
    }

    @Override
    public void addEmailBoxAndSearch(String search, String name,String box_creat_user) {
        //仅查询客户箱
        List<searchEmail> searchEmails = emailDao.selectSearchBySendAddress1(search);
        if(searchEmails.size()==0){
            searchEmail searchEmail=new searchEmail();
            searchEmail.setSenderAddresser(search);
            searchEmail.setSub(0);
            searchEmail.setIsAdjunct(-1);
            searchEmail.setEmail_class(0);
//            emailDao.insertSearch(searchEmail);
            email_box box=new email_box();
            box.setSelect_rule(searchEmail.getSearch_id());
            box.setBox_creat_date(ServerciEmailUnit.getNowSqlDate());
            box.setBox_name(name);
            box.setBox_grade(3);
            box.setBox_creat_user(box_creat_user);
            box.setUser_id("-1");
//            emailDao.insertBox(box);
        }
    }



    //测试pop是否可用
    @Override
    public String popLink(email_Pop3 pop3, UserEntity user){
        String re = popTest(pop3);
        if(re.equals("")){
            pop3.setPop3_user_id(user.getCode());
            pop3.setSend_name(user.getName());
            pop3.setPop3_useStatus(1);
            updatePop3(pop3);
        }
        return re;
    }
    //测试pop是否可用
    @Override
    public String popTest(email_Pop3 pop3){
        String wrong="";//错误信息
        String re="";//返回数据
        Store store=null;
        Folder folder=null;
        try {
            for(int i =0;i<3;i++){
                try{
                    store = servicerLink.getStore(pop3,this);//进行三次连接，三次索要
                    if(store!=null){
                        break;
                    }
                }catch (Exception e){
                    if(i==3){
                        wrong=e.toString();
                    }
                }
            }

            folder = store.getFolder("INBOX");//获取收件箱
            folder.open(Folder.READ_WRITE); // 设置对邮件帐户的访问权限
        }catch (Exception e){
            wrong=e.toString();
        }finally {
            try {
                if (folder!=null) {
                    folder.close(true);
                }
            }catch (Exception e){
                wrong=e.toString();
            }
        }
        if(!wrong.equals("")){
            if(wrong.contains("Please using authorized code to login")){
                re="授权代码或密码不正确登录，请仔细核对";
            }else if(wrong.contains(" Couldn't connect to host, port")){
                re="服务器或端口号错误，请仔细核对";
            }else if(wrong.contains("Login fail. Password is incorrect or service is not open")){
                re="账号或密码错误，请仔细核对";
            }else{
                re="其他错误，请仔细核对";
            }
        }
        return re;
    }
    //测试smtp是否可用
    @Override
    public String smtpLink(email_smtp smtp,UserEntity user){
        String wrong="";
        String re="";
        Transport transport=null;
        try {
            Session session= ServiceSendEmail.smtptest(smtp);
            transport = session.getTransport();
            //设置发件人的账户名和密码
            transport.connect(smtp.getEmail_name(), smtp.getEmail_password());
        }catch (Exception e){
            wrong=e.toString();
        }finally {
            try{
                if(transport!=null){
                    transport.close();
                }}catch (Exception e){
                System.out.println(e);
                wrong=e.toString();
            }
        }
        if(!wrong.equals("")){
            if(wrong.contains("Please enter your authorization code to login")){
                re="授权代码或密码或账号不正确登录，请仔细核对";
            }else if(wrong.contains(" Couldn't connect to host, port")){
                re="服务器或端口号错误，请仔细核对";
            }else if(wrong.contains("Login fail. Password is incorrect or service is not open")){
                re="账号或密码错误，请仔细核对";
            }else{
                re="其他错误，请仔细核对";
            }
        }
        if(re.equals("")){
            smtp.setSmtp_user_id(user.getCode());
            smtp.setSmtp_useStatus(1);
            updateStmp(smtp);
        }
        return re;
    }

    @Override
    public Integer selectNoRead(List<email_Pop3> pop3s) {
        return emailDao.selectNoRead(pop3s);
    }
    /**
     * 30天、60天未联系的客户
     *
     * @return
     */
    @Override
    public Map<String, Object> getCountContact(UserEntity user) {
        Map<String, Object> map=new HashMap<>();
        map.put("contact30",0);
        map.put("contact60",0);
        return map;
    }

    @Override
    public List<email_Pop3> selectAllEmail_Pop3NotStatue() {
        return emailDao.selectAllEmail_Pop3NotStatue();
    }


    public void checkAuto() throws ParseException {
        List<emailAuto> emailAutos = emailDao.selectAuto();
        if(emailAutos!=null&&emailAutos.size()>0){
            for(emailAuto auto:emailAutos){
                String createDate = auto.getCreateDate();
                //第三重判断，时间判断   根据设置收取的时间条件  0：默认三个月；1:6个月；2:9个月；3：全部
                Date dNowdate = new Date(); //当前时间bai
                Date dBeforedate = new Date();
                Calendar calendar = Calendar.getInstance(); //得到日历du
                calendar.setTime(dNowdate);//把当前时间赋给日历
                calendar.add(calendar.DAY_OF_WEEK, -1); //设置为前1天
                dBeforedate = calendar.getTime(); //得到前1天的时间
                long time = dBeforedate.getTime();//1天前的日期
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//注意月份是MM
                Date create = simpleDateFormat.parse(createDate);
                long time1 = create.getTime();//创建日期
                if ((time - time1) > 0) {
                    //一天前 删除
                    emailDao.deleteAuto(auto);
                }else{
                    //一天内  不用管
                }
            }
        }
    }


    @Override
    public List<AnnexEntity> selectAllFileNmae() {
        return  emailDao.selectAllFileNmae();
    }

    @Override
    public String saveEmail(email_message message,UserEntity user,int email_class) {
        String retu="success";
        try{
            HashMap<String, String> aduncts = message.getAduncts();
            Map<String, String> sendAddres = message.getSendAddres();//收件人
            email_smtp smtp = this.selectStmpById(message.getStmpId());
            String sendN="";
            String sendA="";
            Iterator<Map.Entry<String, String>> iterator1 = sendAddres.entrySet().iterator();
            while (iterator1.hasNext()){
                Map.Entry<String, String> next = iterator1.next();
                String name = next.getKey();
                String address = next.getValue();
                sendN+=name+";";
                sendA+=address+";";
            }
            List<String> copyAddress = message.getCopyAddress();
            String copy="";
            if(copyAddress.size()>0){
                for(String cp:copyAddress){
                    copy+=cp+",";
                }
            }
            List<String> darkAddress = message.getDarkAddress();
            String dark="";
            if(darkAddress.size()>0){
                for(String dar:darkAddress){
                    dark+=dar+",";
                }
            }
            List<email_Pop3> pop3s = this.selectAllEmail_Pop3byUserCode(user.getCode());
            //元数据存放
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = sdf.format(new Date());
            email_email email=new email_email(-1,smtp.getSmtp_server(),-1,-1,-1,-1,email_class,message.getSubject(),user.getCode(),smtp.getEmail_adress(),sendN,sendA,null,copy,dark,-1,user.getCode(),format,null,format,message.getCharset(),message.getIsmore(),smtp.getSmtp_id(),0,message.getPictures().size(),message.getAduncts().size(),1,null,0);
            if(message.getEmail_id()!=0){
                Integer emailClass=11;
                List<email_email> emails=new ArrayList<>();
                email_email e=new email_email();
                e.setEmail_id(message.getEmail_id());
                emails.add(e);
                changeEmailClass change=new changeEmailClass(emailClass,emails);
                this.updateEmailClass(change);
            }
            email.setRecipientAddress(sendA);
            this.addEmail_email(email);
            String pathName = "/email/draft/" + pop3s.get(0).getEmail_adress() + "/" + email.getEmail_id()+ "/";

            //存储附件
            if(aduncts.size()>0){
                Iterator<Map.Entry<String, String>> iterator = aduncts.entrySet().iterator();
                while (iterator.hasNext()){
                    Map.Entry<String, String> next = iterator.next();
                    String name = next.getKey();
                    String address = next.getValue();
                    String randomFileName = ServerciEmailUnit.getRandomFileName();
                    String ftpPath= iFtpService.uploadEmailAdjunct(pathName, randomFileName, new FileInputStream(new File(address)));
                    email_adjunct adjunct=new email_adjunct(email.getEmail_id(),0,1,0,null,null,null,null,name,ftpPath,1);
                    this.insertEmail_adjunct(adjunct);
                }
            }
            //存储正文
            email_adjunct context=new email_adjunct(email.getEmail_id(),0,0,1,null,message.getContenct(),null,null,null,null,1);
            this.insertEmail_adjunct(context);}catch (Exception e){
            retu="wrong";
        }
        return retu;
    }

    @Override
    public List<email_email> selectCustorShowEmailByPage(ArrayList<String> emails) {
        return emailDao.selectCustorShowEmailByPage(emails);
    }

    @Override
    public Integer checkEmailMore(email_email email) {
        return emailDao.checkEmailMore(email);
    }

    @Override
    public void deleteContext(Integer emailID) {
        emailDao.deleteContext(emailID);
    }

    @Override
    public List<email_email> selectEmailByParam(email_email email) {
        return emailDao.selectEmailByParam(email);
    }

    @Override
    public String SearchTerm(Integer pop3_id, Date startTime, Date endTime, Integer high,Integer type) {
        String read="";
        if(type==0){
            read="INBOX";
        }else{
            read="已发送";
        }
        SearchTerm comparisonTermGe = new SentDateTerm(ComparisonTerm.GE, startTime);
        SearchTerm comparisonTermLe = new SentDateTerm(ComparisonTerm.LE, endTime);
        SearchTerm comparisonAndTerm = new AndTerm(comparisonTermGe, comparisonTermLe);
        email_Pop3 pop3 = emailDao.selectPOP3Bypop3_id(pop3_id);
        Folder folder = servicerLink.getFolder(pop3,read);
        IMAPFolder inbox = (IMAPFolder) folder;
        Message[] messages=null;
        ArrayList<Message> arr=new ArrayList();
        try {
            messages= folder.search(comparisonAndTerm);
            if(messages.length>high){
                return "超过设置长度";
            }
            for (Message m : messages) {
                if(m.getSentDate().after(startTime)&&m.getSentDate().before(endTime)){
                    arr.add(m);
                }
            }
        }catch (Exception e){
            System.out.println("失败");
        }
        int wrong=0;
        List<Integer> firstEmail=null;
        Message[] message=new Message[arr.size()];
        for(int i=0;i<arr.size();i++){
            message[i]=arr.get(i);
        }
        boolean b = downMessages(message, pop3, inbox, -1, firstEmail, "INBOX", false);
        return b+"";
    }
}
